package com.seelyn.ddvideo.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class DownloadMain {

    private Logger LOG = LoggerFactory.getLogger(DownloadMain.class);
    // 定义下载资源的路径
    private String path;
    // 指定所下载的文件的保存位置
    private String targetFile;
    private String targetDir;
    // 定义需要使用多少线程下载资源
    private int threadNum = 4;

    // 定义下载的线程对象
    private ExecutorService threadPool;


    public DownloadMain(String path, String targetDir, String targetFile, int threadNum) {
        this.path = path;
        this.threadNum = threadNum;
        this.targetFile = targetFile;
        this.targetDir = targetDir;
        File dirFile = new File(targetDir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        this.threadPool = Executors.newFixedThreadPool(threadNum);
    }

    public void download(CompleteHandler handler) throws IOException {

        File file = new File(targetDir + "/" + targetFile);
        HttpURLConnection connection = (HttpURLConnection) new URL(path).openConnection();
        connection.setRequestMethod("GET");
        int contentLength = connection.getContentLength();
        if (contentLength < 1) {
            throw new IOException("contentLength size is 0");
        }

        int range = contentLength / threadNum;
        for (int i = 0; i < threadNum; i++) {
            int start = i * range;
            int end = start + range;
            if (i == (threadNum - 1)) {
                end = contentLength - 1;
            }
            threadPool.submit(new DownloadThread(path, file, start, end));
        }

        threadPool.shutdown();
        try {//等待直到所有任务完成
            threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (handler != null) {
            handler.doProcess();
        }

    }

}
